// hooks/useZoom.js
import * as d3 from 'd3'
import { ref } from 'vue'

export function useZoom(svgRef) {
    const zoom = ref(null)

    const initZoom = () => {
        const zoomBehavior = d3.zoom()
            .scaleExtent([0.1, 3])
            .on('zoom', (event) => {
                // 确保 svgRef.value 是 D3 可操作的对象
                d3.select(svgRef.value).select('g.zoom-group').attr('transform', event.transform)
            })

        zoom.value = zoomBehavior

        // 使用 d3.select() 确保 svgRef.value 是 D3 可操作的对象
        d3.select(svgRef.value).call(zoomBehavior)
    }

    const zoomIn = () => {
        if (!svgRef.value || !zoom.value) return
        d3.select(svgRef.value).transition().duration(300).call(zoom.value.scaleBy, 1.2)
    }

    const zoomOut = () => {
        if (!svgRef.value || !zoom.value) return
        d3.select(svgRef.value).transition().duration(300).call(zoom.value.scaleBy, 0.8)
    }

    const resetZoom = () => {
        if (!svgRef.value || !zoom.value) return
        d3.select(svgRef.value).transition().duration(300).call(zoom.value.transform, d3.zoomIdentity)
    }

    return {
        zoom,        // 返回 zoom 变量
        initZoom,
        zoomIn,
        zoomOut,
        resetZoom
    }
}
